package com.company.aicrawlers.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.ProductCategoryDict;
import com.company.aicrawlers.mapper.ProductCategoryDictMapper;
import com.company.aicrawlers.service.ProductCategoryDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 产品类别字典服务实现类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@Service
public class ProductCategoryDictServiceImpl implements ProductCategoryDictService {
    
    @Autowired
    private ProductCategoryDictMapper categoryDictMapper;
    
    @Override
    public List<ProductCategoryDict> getTreeList() {
        // 查询所有启用的类别
        LambdaQueryWrapper<ProductCategoryDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategoryDict::getStatus, 1)
               .orderByAsc(ProductCategoryDict::getSortOrder);
        
        List<ProductCategoryDict> allCategories = categoryDictMapper.selectList(wrapper);
        
        // 构建树形结构（简单实现，只支持两级）
        List<ProductCategoryDict> treeList = new ArrayList<>();
        
        // 先添加顶级类别
        for (ProductCategoryDict category : allCategories) {
            if (category.getParentId() == 0) {
                treeList.add(category);
            }
        }
        
        log.info("获取类别树形结构，总数: {}", treeList.size());
        return treeList;
    }
    
    @Override
    public List<ProductCategoryDict> getChildren(Long parentId) {
        List<ProductCategoryDict> children = categoryDictMapper.selectByParentId(parentId);
        log.info("获取子类别，父ID: {}, 子类别数: {}", parentId, children.size());
        return children;
    }
    
    @Override
    public ProductCategoryDict getByCategoryName(String categoryName) {
        return categoryDictMapper.selectByCategoryName(categoryName);
    }
    
    @Override
    public List<ProductCategoryDict> getAllEnabled() {
        LambdaQueryWrapper<ProductCategoryDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategoryDict::getStatus, 1)
               .orderByAsc(ProductCategoryDict::getLevel)
               .orderByAsc(ProductCategoryDict::getSortOrder);
        
        return categoryDictMapper.selectList(wrapper);
    }
    
    @Override
    public ProductCategoryDict getById(Long id) {
        ProductCategoryDict category = categoryDictMapper.selectById(id);
        if (category == null) {
            throw new BusinessException("类别不存在");
        }
        return category;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long create(ProductCategoryDict category) {
        // 验证必填项
        if (StrUtil.isBlank(category.getCategoryName())) {
            throw new BusinessException("类别名称不能为空");
        }
        
        // 检查同名类别
        LambdaQueryWrapper<ProductCategoryDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategoryDict::getCategoryName, category.getCategoryName())
               .eq(ProductCategoryDict::getParentId, category.getParentId() == null ? 0 : category.getParentId());
        
        ProductCategoryDict exist = categoryDictMapper.selectOne(wrapper);
        if (exist != null) {
            throw new BusinessException("同名类别已存在");
        }
        
        // 设置默认值
        if (category.getParentId() == null) {
            category.setParentId(0L);
        }
        
        if (category.getLevel() == null) {
            category.setLevel(category.getParentId() == 0 ? 1 : 2);
        }
        
        if (category.getSortOrder() == null) {
            category.setSortOrder(0);
        }
        
        if (category.getStatus() == null) {
            category.setStatus(1);
        }
        
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        
        categoryDictMapper.insert(category);
        log.info("创建类别成功，ID: {}, 名称: {}", category.getCategoryId(), category.getCategoryName());
        
        return category.getCategoryId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProductCategoryDict category) {
        // 检查是否存在
        ProductCategoryDict exist = categoryDictMapper.selectById(category.getCategoryId());
        if (exist == null) {
            throw new BusinessException("类别不存在");
        }
        
        // 验证必填项
        if (StrUtil.isBlank(category.getCategoryName())) {
            throw new BusinessException("类别名称不能为空");
        }
        
        // 检查同名（排除自己）
        LambdaQueryWrapper<ProductCategoryDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategoryDict::getCategoryName, category.getCategoryName())
               .eq(ProductCategoryDict::getParentId, category.getParentId() == null ? exist.getParentId() : category.getParentId())
               .ne(ProductCategoryDict::getCategoryId, category.getCategoryId());
        
        ProductCategoryDict duplicate = categoryDictMapper.selectOne(wrapper);
        if (duplicate != null) {
            throw new BusinessException("同名类别已存在");
        }
        
        category.setUpdateTime(LocalDateTime.now());
        categoryDictMapper.updateById(category);
        
        log.info("更新类别成功，ID: {}, 名称: {}", category.getCategoryId(), category.getCategoryName());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 检查是否存在
        ProductCategoryDict category = categoryDictMapper.selectById(id);
        if (category == null) {
            throw new BusinessException("类别不存在");
        }
        
        // 检查是否有子类别
        LambdaQueryWrapper<ProductCategoryDict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductCategoryDict::getParentId, id);
        
        Long childCount = categoryDictMapper.selectCount(wrapper);
        if (childCount > 0) {
            throw new BusinessException("该类别下有子类别，无法删除");
        }
        
        // TODO: 检查是否有产品使用该类别（需要查询product表）
        
        categoryDictMapper.deleteById(id);
        log.info("删除类别成功，ID: {}, 名称: {}", id, category.getCategoryName());
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("请选择要删除的类别");
        }
        
        for (Long id : ids) {
            delete(id);
        }
        
        log.info("批量删除类别成功，数量: {}", ids.size());
    }
}

